<template>
  <el-container>
    <el-header height="28">
      <div>
        <el-row :gutter="1">
          <el-col :span="20">
            <el-tooltip
                class="box-item"
                effect="dark"
                content="点击显示/隐藏左侧目录树"
                placement="bottom">
              <el-button type="plain" text="true" circle @click="handleExpandClick" style="display: inline-block; ">
                <el-icon size="20">
                  <DArrowRight v-show="isExpand" />
                  <DArrowLeft v-show="isFold"/>
                </el-icon>
              </el-button>
            </el-tooltip>

            <el-input placeholder="请输入..." type="text" maxlength="50"
                      v-model="title" style="display: inline-block; width: 80%;">
            </el-input>
          </el-col>
          <el-col :span="4" class="right" style="padding: 0;">
            <!-- 笔记信息提示 -->
            <el-popover :width="260" trigger="click">
              <template #reference>
                <el-button type="plain" text="true" circle>
                  <el-icon size="18"><InfoFilled /></el-icon>
                </el-button>
              </template>
              <el-table :data="noteInfo">
                <el-table-column width="80" property="key" label="" />
                <el-table-column width="150" property="value" label="" />
              </el-table>
            </el-popover>
            <!-- 多功能下拉菜单 -->
            <el-dropdown @command="handleMoreCommand" trigger="hover"  style="padding: 5px;">
              <span class="el-dropdown-link" >
                  <el-icon size="20"><MoreFilled /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="exportHtml">
                    <el-icon size="18"><DocumentCopy /></el-icon>导出为 Html 文件
                  </el-dropdown-item>
                  <el-dropdown-item command="exportTxt">
                    <el-icon size="18"><Document /></el-icon>导出为 Txt 文件
                  </el-dropdown-item>
                  <el-dropdown-item command="importBackupData" divided="true">
                    <el-icon size="18"><Download /></el-icon>导入笔记数据
                  </el-dropdown-item>
                  <el-dropdown-item command="backups">
                    <el-icon size="18"><Files /></el-icon>备份数据到本地
                  </el-dropdown-item>
                  <el-dropdown-item command="clearAll" divided="true">
                    <el-icon size="18"><Failed /></el-icon>清空数据【请先备份】
                  </el-dropdown-item>
                  <el-dropdown-item command="showAboutDlg" divided="true">
                    <el-icon size="18"><Warning /></el-icon>关于我们
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
      </div>
    </el-header>
    <el-main id="main-editor">
      <Toolbar
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
          style="border-bottom: 1px solid #ccc">
      </Toolbar>
      <Editor
          :defaultConfig="editorConfig"
          :mode="mode"
          v-model="valueHtml"
          style="height: 82vh;"
          @onCreated="handleCreated"
          @onChange="handleChange"
          @onDestroyed="handleDestroyed"
          @onFocus="handleFocus"
          @onBlur="handleBlur">
      </Editor>
    </el-main>
  </el-container>
  <!-- about弹窗 -->
  <AboutDlg v-model="openAboutDlg" @dlg-close="openAboutDlg=false"/>
</template>

<script>

import '@wangeditor/editor/dist/css/style.css';
import {onBeforeUnmount, getCurrentInstance, ref, shallowRef, onMounted, reactive, toRefs, nextTick} from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import AboutDlg from '@/views/about-view.vue';

export default {
  components: { Editor, Toolbar, AboutDlg },
  setup() {
    const { proxy } = getCurrentInstance();
    const state = reactive({
      title: '',
      typeId: '',
      hidePanl: true,
      isExpand: false,
      isFold: true,
      openAboutDlg: false,
      noteInfo: [
        { key: '创建时间', value: '2016/05/04 10:10:05' },
        { key: '更新时间', value: '2016/05/04 10:10:05' },
        { key: '字数', value: '123' },
      ]
    })

    // 编辑器实例，必须用 shallowRef，重要！
    const editorRef = shallowRef();

    onMounted(() => {
     /* proxy.$bus.on('typeId', (e) => {
        state.typeId = e
        proxy.$alert('接收到入参typeId=' + state.typeId)
      })*/

      nextTick(()=>{
        //state.hHeight = document.documentElement.clientHeight - 115;
        //proxy.$alert('当前容器可视高度是' + state.hHeight)
      })

      //ctrl + s 快捷操作
      document.onkeydown = function(e) {
        var e1 = e || event || window.event
        var currKey = e1.keyCode || e1.which || e1.charCode
        if(currKey == 83 && (e1.ctrlKey || e1.metaKey)) {
          //_this.search()
          window.event.returnValue = false  // 阻止浏览器默认行为
          proxy.$alert('快捷保存开始')
        }
      }
    })
    // 内容 HTML
    const valueHtml = ref('<p>hello</p>');

    // 模拟 ajax 异步获取内容
    onMounted(() => {
      setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>';

        //打印所有菜单项
        const editor = editorRef.value;
        console.log('所有工具菜单', editor.getAllMenuKeys())
      }, 1500);
    });
    //
    const handleExpandClick = () => {
      state.hidePanl = !state.hidePanl
      state.isExpand = !state.hidePanl
      state.isFold = state.hidePanl

      proxy.$bus.emit('hidePanl', state.hidePanl)
      //console.log("hidePanl",  state.hidePanl )
    }

    const handleMoreCommand = (e) => {
      if(e == 'showAboutDlg') {
        state.openAboutDlg = true
        return
      }
      proxy.$alert('点击了下拉事件: ' + e)
    }

    const toolbarConfig = {
      //去除工具栏
      /*excludeKeys: ["group-more-style",'group-video','redo','undo', 'todo', 'blockquote',
        'emotion', 'lineHeight', 'group-indent', 'group-justify', 'underline', 'uploadImage'
      ]*/
      toolbarKeys: [
        // 菜单 key
        'headerSelect',
        'bold', // 加粗
        'italic', // 斜体
        'through', // 删除线
        //'underline', // 下划线
        'bulletedList', // 无序列表
        'numberedList', // 有序列表
        'color', // 文字色彩
        //'insertLink', // 插入链接
        'fontSize', // 字体大小
        //'lineHeight', // 行高
        'insertImage', // 网络图片
        //'uploadImage', // 上传图片
        //'delIndent', // 缩进
        //'indent', // 增进
        //'deleteImage', //删除图片
        //'divider', // 分割线
        'insertTable', // 插入表格
        //'group-justify', // 居中对齐
        //'justifyJustify', // 两端对齐
        //'justifyLeft', // 左对齐
        //'justifyRight', // 右对齐
        'undo', // 撤销
        //'redo', // 重做
        'clearStyle', // 革除格局
        'codeBlock',  //代码块
        'fullScreen', // 全屏
      ],
    }

    const editorConfig = {
      placeholder: '请输入内容...',
      // readOnly: true,
      MENU_CONF: {
        // 配置上传服务器地址
        uploadImage: {
          // 小于该值就插入 base64 格局（而不上传），默认为 0
          base64LimitSize: 5 * 1024, // 5kb
          // 单个文件的最大体积限度，默认为 2M
          // maxFileSize: 1 * 1024 * 1024, // 1M
          // // 最多可上传几个文件，默认为 100
          // maxNumberOfFiles: 5,
          // 抉择文件时的类型限度，默认为 ['image/*'] 。如不想限度，则设置为 []
          allowedFileTypes: ['image/*'],
          // 自定义上传
        },
      },
    };
    // 组件销毁时，也及时销毁编辑器，重要！
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.destroy();
    });

    const quickSave = () => {
      console.log("word==>", this.word);
      if(this.word == undefined || this.word.trim().length == 0) {
        this.showResult = false
        this.showMsg = false
      }
    }

    // 编辑器回调函数
    const handleCreated = (editor) => {
      //console.log('created', editor);
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    const handleChange = (editor) => {
      console.log('change:', editor.getHtml());
    };
    /*const handleDestroyed = (editor) => {
      console.log('destroyed', editor);
    };
    const handleFocus = (editor) => {
      console.log('focus', editor);
    };
    const handleBlur = (editor) => {
      console.log('blur', editor);
    };
    const customAlert = (info, type) => {
      alert(`【自定义提示】${type} - ${info}`);
    };*/
    /*const customPaste = (editor, event, callback) => {
      console.log('ClipboardEvent 粘贴事件对象', event);

      // 自定义插入内容
      editor.insertText('xxx');

      // 返回值（注意，vue 事件的返回值，不能用 return）
      callback(false); // 返回 false ，阻止默认粘贴行为
      // callback(true) // 返回 true ，继续默认的粘贴行为
    };*/

    const insertText = () => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.insertText('hello world');
    };

    const printHtml = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      console.log(editor.getHtml());
    };

    const disable = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.disable()
    };

    return {
      ...toRefs(state),
      editorRef,
      mode: 'default',
      valueHtml,
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleChange,
      //handleDestroyed,
      //handleFocus,
      //handleBlur,
      //customAlert,
      //customPaste,
      insertText,
      printHtml,
      disable,
      quickSave,
      handleExpandClick,
      handleMoreCommand,
    };
  },
};
</script>

<style scoped>
.left { text-align: left; padding: 0px;}
.is-circle { padding: 0px; }
.right { text-align: right; }
::v-deep .el-input__wrapper { border: 0; box-shadow: 0 0 0 0; width: 100%;}
::v-deep .el-row { border-bottom: 1px solid #ccc; }
.el-button { margin: 0 10px; }
.el-header { --el-header-padding: 0 10px 0 10px; }
.el-main { --el-main-padding: 0 10px 0 10px; }
/* 编辑器工具条缩小 */
::v-deep .w-e-bar-item { height: 35px; padding: 0px; }
</style>
